package com.atguigu.chapter11.function;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/26 9:11
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        DataStreamSource<WaterSensor> stream = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                                                                                     new WaterSensor("sensor_1", 2000L, 20),
                                                                                     new WaterSensor("sensor_2", 3000L, 30),
                                                                                     new WaterSensor("sensor_1", 4000L, 40),
                                                                                     new WaterSensor("sensor_1", 5000L, 50),
                                                                                     new WaterSensor("sensor_2", 6000L, 60));
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
    
        Table table = tEnv.fromDataStream(stream);
        
        
        /*table
            .groupBy($("id"))
            .select($("id"), call(MySum.class, $("vc")).as("vc_sum"))
            .execute()
            .print();*/
    
        tEnv.createTemporaryFunction("my_sum", MySum.class);
        /*table
            .groupBy($("id"))
            .select($("id"), call("my_sum", $("vc")).as("vc_sum"))
            .execute()
            .print();*/
    
        tEnv.sqlQuery("select id, my_sum(vc) sum_vc from " + table + " group by id").execute().print();
    
    }
    
    public static class MyAcc{
        public Integer sum = 0;
    }
    
    public static class MySum extends AggregateFunction<Integer, MyAcc>{
    
        // 返回最终聚合的结果
        @Override
        public Integer getValue(MyAcc acc) {
            return acc.sum;
        }
        // 初始化累加器
        @Override
        public MyAcc createAccumulator() {
            return new MyAcc();
        }
        
        // 累加
        public void accumulate(MyAcc acc, Integer v){
            acc.sum += v;
        }
    }
    
}
/*
hello  5
atguigu  6

 */
